import { GoodsCateService } from 'src/service/goods-cate/goods-cate.service';
import { GoodsService } from 'src/service/goods/goods.service';
import { ResponseInterceptor } from './../../../interceptor/response/response.interceptor';
import { Controller, Get, Query, UseInterceptors } from '@nestjs/common';
import config from 'src/config/config';
import * as mongoose from 'mongoose';

@Controller(`${config.shopApiPath}/category`)
@UseInterceptors(ResponseInterceptor)
export class CategoryController {
    constructor(private readonly goodsService: GoodsService, private readonly goodsCateService: GoodsCateService) {}
    @Get('/goods')
    async getAllCateGoodsList(@Query() query) {
        const { page = 1, pageSize = 10, cate_id, $sort, $match } = query;
        const cateList = await this.goodsCateService.getModel().aggregate([
            { $match: { _id: new mongoose.Types.ObjectId(cate_id) } },
            {
                $lookup: {
                    localField: '_id',
                    foreignField: 'pid',
                    from: 'goods_cate',
                    as: 'children',
                },
            },
        ]);
        const cateIn = cateList
            .reduce((pre, item) => [...pre, item._id, ...item.children.map((item1) => item1._id)], [])
            .map((item) => new mongoose.Types.ObjectId(item));

        const findGoodsOptions: any[] = [
            { $match: { cate_id: { $in: cateIn }, ...JSON.parse($match) } },
            { $skip: (+page - 1) * +pageSize },
            { $limit: +pageSize },
            { $lookup: { localField: '_id', foreignField: 'goods_id', from: 'goods_image', as: 'goods_image_list' } },
        ];
        if ($sort !== '{}') {
            findGoodsOptions.unshift({ $sort: JSON.parse($sort) });
        }
        const goodsList = await this.goodsService.getModel().aggregate(findGoodsOptions);
        const total = await this.goodsService
            .getModel()
            .find({ cate_id: { $in: cateIn }, ...JSON.parse($match) })
            .count();
        return { data: goodsList, total };
    }
    @Get('/byParentId')
    async getCategoriesByParentId(@Query() query) {
        const { parentId } = query;
        const cateList = await this.goodsCateService.getModel().aggregate([
            { $match: { _id: new mongoose.Types.ObjectId(parentId) } },
            {
                $lookup: {
                    localField: '_id',
                    foreignField: 'pid',
                    from: 'goods_cate',
                    as: 'children',
                },
            },
        ]);
        const categories = cateList.reduce((pre, item) => [...pre, item, ...item.children.map((item1) => item1)], []);
        return categories;
    }
}
